import * as uuid from "uuid";
import type Typings from "../../typings";

import ResStatus from "./res";

class Common<T> {
  Model: T & Typings.Common.plainObj;

  constructor(Model: T & Typings.Common.plainObj) {
    this.Model = Model;
  }

  // 生成一个 uuid
  static CreateUuid: () => string = () => uuid.v4();

  // 获取当前登录的用户id
  getLoginUserId: (req: Typings.Express.ConvertRequest) => string = (req) => {
    const { loginUser } = <Typings.Express.ConvertRequest>req;
    return loginUser?.id || "";
  };

  // 查询总数量
  Count: (query: Typings.Common.plainObj) => any = (query = {}) => {
    return this.Model.countDocuments(query);
  };

  // 查询
  Find: (query: Typings.Common.plainObj) => any = (query = {}) => {
    return this.Model.find(query);
  };

  // 保存
  SaveOne: (data: Typings.Common.plainObj) => any = (data = {}) => {
    const id = Common.CreateUuid();
    return new (this.Model as any)({ id, ...data }).save();
  };

  // 单个更新
  UpdateOne: (
    query: Typings.Common.plainObj,
    updateContent: Typings.Common.plainObj
  ) => any = (query = {}, updateContent = {}) => {
    return this.Model.findOneAndUpdate(query, updateContent, {
      new: true,
      runValidators: true /* 触发验证*/,
    });
  };

  // 单个删除
  RemoveOne: (query: Typings.Common.plainObj) => any = (query = {}) => {
    return this.Model.findOneAndDelete(query);
  };

  // 批量删除
  DeleteMany: (query: Typings.Common.plainObj) => any = (query: {}) => {
    return this.Model.deleteMany(query);
  };

  // 批量更新
  updateMany: (
    query: Typings.Common.plainObj,
    updateContent: Typings.Common.plainObj
  ) => any = (query = {}, updateContent = {}) => {
    return this.Model.updateMany(query, updateContent);
  };
}

export { ResStatus, Common };
